//
//  ZCShipmentDetailViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/9/10.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCShipmentDetailViewController.h"
#import "ZCShipmentTopTableViewCell.h"
#import "ZCShipmentCarInfoTableViewCell.h"
#import "ZCShipmentListModel.h"


static NSString *topCellID = @"ZCShipmentTopTableViewCell";
static NSString *carInfoCellID = @"ZCShipmentCarInfoTableViewCell";

@interface ZCShipmentDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *handleView;
@property (nonatomic, strong) UIButton *commitButton;
@property (nonatomic, strong) ZCShipmentModel *shipModel;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ZCShipmentDetailViewController
#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT - space(170)) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        
        [_tableView registerClass:[ZCShipmentTopTableViewCell class] forCellReuseIdentifier:topCellID];
        [_tableView registerClass:[ZCShipmentCarInfoTableViewCell class] forCellReuseIdentifier:carInfoCellID];
    }
    return _tableView;
}

- (UIView *)handleView {
    if (!_handleView) {
        _handleView = [[UIView alloc] init];
        _handleView.backgroundColor = [UIColor whiteColor];
    }
    return _handleView;
}

- (UIButton *)commitButton {
    if (!_commitButton) {
        _commitButton = [[UIButton alloc] init];
        [_commitButton setTitle:@"确认发运" forState:UIControlStateNormal];
        [_commitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _commitButton.titleLabel.font = [UIFont systemFontOfSize:FontSize(30)];
        [_commitButton setBackgroundColor:ZCColor(0xff8213, 1)];
        _commitButton.layer.masksToBounds = YES;
        _commitButton.layer.cornerRadius = space(6);
        [_commitButton addTarget:self action:@selector(commitButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _commitButton.timeInterval = 3;
    }
    return _commitButton;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = ZCColor(0xf7f8fb, 1);
    self.navigationItem.title = @"指令详情";
//    self.navigationController.navigationBar.translucent = NO;
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [backButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.handleView];
    [self.handleView addSubview:self.commitButton];
    __weak typeof(self)weakSelf = self;
    [_handleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        make.right.equalTo(weakSelf.view.mas_right);
        make.bottom.equalTo(weakSelf.view.mas_bottom);
        make.height.mas_equalTo(space(150));
    }];
    
    [_commitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.handleView.mas_left).offset(space(80));
        make.right.equalTo(weakSelf.handleView.mas_right).offset(-space(80));
        make.centerY.equalTo(weakSelf.handleView.mas_centerY);
        make.height.mas_equalTo(space(90));
    }];
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    [self loadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
}

#pragma mark - 网络请求
- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.Id forKey:@"condition[key]"];
    NSString *houseId = [[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId];
    if (houseId.length > 0) {
        [param setObject:houseId forKey:@"houseId"];
    }
    

    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:ShipmentDetail params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                weakSelf.shipModel = [ZCShipmentModel yy_modelWithDictionary:responseObject[@"data"]];
                if ([weakSelf.shipModel.status isEqualToString:@"BS_DISPATCH"]) {
                    weakSelf.handleView.hidden = YES;
                    weakSelf.tableView.frame = CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT - space(20));
                }
                [weakSelf.tableView reloadData];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - 按钮点击
- (void)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)commitButtonClick:(UIButton *)sender {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.shipModel.Id forKey:@"condition[key]"];

    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:ShipmentCommit params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                weakSelf.shipModel = [ZCShipmentModel yy_modelWithDictionary:responseObject[@"data"]];
                if ([weakSelf.shipModel.status isEqualToString:@"BS_DISPATCH"]) {
                    weakSelf.handleView.hidden = YES;
                    weakSelf.tableView.frame = CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT - space(20));
                }
                [weakSelf.tableView reloadData];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return self.shipModel.otmOrderReleaseList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ZCShipmentTopTableViewCell *topCell = [tableView dequeueReusableCellWithIdentifier:topCellID forIndexPath:indexPath];
        topCell.selectionStyle = UITableViewCellSelectionStyleNone;
        topCell.shipM = self.shipModel;
        return topCell;
    }else {
        ZCShipmentCarInfoTableViewCell *carInfoCell = [tableView dequeueReusableCellWithIdentifier:carInfoCellID forIndexPath:indexPath];
        carInfoCell.selectionStyle = UITableViewCellSelectionStyleNone;
        ZCShipmentOrderModel *orderM = self.shipModel.otmOrderReleaseList[indexPath.row];
        carInfoCell.orderModel = orderM;
        
        return carInfoCell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return space(708);
    }
    return space(450);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return CGFLOAT_MIN;
    }
    return space(94);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return [[UIView alloc] init];
    }
    return [self headerView];
}

#pragma mark - section headerView
- (UIView *)headerView {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, space(94))];
    headerView.backgroundColor = ZCColor(0xf7f8fb, 1);
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(space(20), 0, SCREENWIDTH - space(40), space(94))];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.masksToBounds = YES;
    bgView.layer.cornerRadius = space(6);
    [headerView addSubview:bgView];
    
    UIImageView *lineImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, space(90), bgView.bounds.size.width, space(4))];
    lineImageV.image = [self drawLineByImageView:lineImageV];
    [bgView addSubview:lineImageV];
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, bgView.bounds.size.width, space(90))];
    titleView.backgroundColor = [UIColor whiteColor];
    [bgView addSubview:titleView];
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"车辆信息";
    titleLabel.textColor = ZCColor(0x000000, 0.87);
    titleLabel.font = [UIFont systemFontOfSize:FontSize(28)];
    [titleView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleView.mas_left).offset(space(40));
        make.centerY.equalTo(titleView.mas_centerY);
    }];

    return headerView;
}

#pragma mark - 画虚线
- (UIImage *)drawLineByImageView:(UIImageView *)imageView{
    UIGraphicsBeginImageContext(imageView.frame.size); //开始画线 划线的frame
    [imageView.image drawInRect:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)];
    //设置线条终点形状
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    // 5是每个虚线的长度 1是高度
    CGFloat lengths[] = {5,1};
    CGContextRef line = UIGraphicsGetCurrentContext();
    // 设置颜色
    CGContextSetStrokeColorWithColor(line, [UIColor colorWithWhite:0.408 alpha:1.000].CGColor);
    CGContextSetLineDash(line, 0, lengths, 2); //画虚线
    CGContextMoveToPoint(line, 0.0, 2.0); //开始画线
    CGContextAddLineToPoint(line, SCREENWIDTH - 10, 2.0);
    
    CGContextStrokePath(line);
    // UIGraphicsGetImageFromCurrentImageContext()返回的就是image
    return UIGraphicsGetImageFromCurrentImageContext();
}

@end
